package com.example.blog.service.impl;

import com.example.blog.entity.Category;
import com.example.blog.mapper.CategoryMapper;
import com.example.blog.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category createCategory(String name, String description) {
        if (categoryMapper.existsByName(name)) {
            throw new RuntimeException("分类已存在: " + name);
        }

        Category category = new Category();
        category.setName(name);
        category.setDescription(description);
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public Category updateCategory(Long id, String name, String description) {
        Category category = findById(id);

        // 检查新名称是否已存在（如果名称已更改）
        if (!category.getName().equals(name) && categoryMapper.existsByName(name)) {
            throw new RuntimeException("分类已存在: " + name);
        }

        category.setName(name);
        category.setDescription(description);
        categoryMapper.update(category);
        return category;
    }

    @Override
    public void deleteCategory(Long id) {
        Category category = findById(id);
        categoryMapper.deleteById(id);
    }

    @Override
    public Category findById(Long id) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在: " + id);
        }
        return category;
    }

    @Override
    public Category findByName(String name) {
        Category category = categoryMapper.selectByName(name).orElse(null);
        if (category == null) {
            throw new RuntimeException("分类不存在: " + name);
        }
        return category;
    }

    @Override
    public List<Category> findAll() {
        return categoryMapper.selectAll();
    }

    @Override
    public boolean existsByName(String name) {
        return categoryMapper.existsByName(name);
    }

}